//
//  OtherViewController.m
//  Runone
//
//  Created by runone01 on 16/8/30.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "OtherViewController.h"
#import "RequestHelper.h"
#import "MJExtension.h"
#import "ParModel.h"
#import "EventBaseInfo.h"
#import "MapPointViewController.h"
#import "CityDirectionController.h"
#import "TableOperation.h"
#import "PileInfo.h"
#import "CommonUtilityjudge.h"
#import "PromptUtil.h"
#import "UITextField+ToolBar.h"
#import "UITextView+ToolBar.h"
#import "SGImagePickerController.h"
//#import "UIColor+ZXLazy.h"
#import "SVProgressHUD.h"
#import "BCNetAPIClient.h"

@interface OtherViewController ()<UIPopoverPresentationControllerDelegate,UITextViewDelegate,UIAlertViewDelegate,UITextFieldDelegate>
@property(nonatomic)NSInteger code;
//输入控件
@property (weak, nonatomic) IBOutlet UITextField *BeginPirTF;
@property (weak, nonatomic) IBOutlet UITextField *DistanceTF;
@property (weak, nonatomic) IBOutlet UITextField *carDirectorTF;
@property (weak, nonatomic) IBOutlet UITextView *DescriptionTV;
@property(nonatomic,strong)MapPointViewController *map;
@property (weak, nonatomic) IBOutlet UIButton *mapBtn;
@property (weak, nonatomic) IBOutlet UIScrollView *imageScrollview;
//相关视图
@property(nonatomic,strong)CityDirectionController *citypop;
@property(nonatomic,strong)EventBaseInfo *info;
@property(nonatomic,copy)NSString  *lo;
@property(nonatomic,copy)NSString  *la;
@property(nonatomic,strong)PromptUtil *PromptUtil;
//选择图片
@property(nonatomic,strong)UIImage *img;
@property(nonatomic,strong)UIImage *loadImage;
@property(nonatomic,strong)UIImageView *iv;

@property(nonatomic,strong)NSArray *imageArray;

@property(nonatomic,strong)UIAlertView *resultAlert;
@end

@implementation OtherViewController

#pragma    --------其他事件上报

- (void)viewDidLoad {
    [super viewDidLoad];
    _carDirectorTF.delegate=self;
//    self.view.backgroundColor=[UIColor colorWithHexString:@"#f7f7f7"];
    UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    label.text=@"其他事件上报";
    label.textAlignment=NSTextAlignmentCenter;
    label.textColor=[UIColor whiteColor];
    self.navigationItem.titleView=label;
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(report)];
    //导航栏颜色
//    self.navigationController.navigationBar.titleTextAttributes = @{UITextAttributeTextColor: [UIColor whiteColor]};
    _PromptUtil=[[PromptUtil alloc] init];
    _DescriptionTV.delegate=self;
    [self AddchooseCityDirectorBtn];
    _info=[[EventBaseInfo alloc] init];
    _info.IncidentType=@"10";
    __weak typeof(self) _weakSelf=self;
    _map=[[MapPointViewController alloc] init];
        _map.FloatBlock=^(CGFloat la,CGFloat lo){
//            _weakSelf.info.Latitude=la;
//            _weakSelf.info.Longitude=lo;
        };
    
    _citypop=[[CityDirectionController alloc] init];
    _citypop.modalPresentationStyle=UIModalPresentationPopover;
    __weak typeof(self) weakSelf=self;
//    _citypop.LineBlock=^(NSInteger index){
//        if (index==0) {
//            weakSelf.carDirectorTF.text=@"广州方向";
//        }
//        if (index==1) {
//            weakSelf.carDirectorTF.text=@"湖南方向";
//       } if (index==2) {
//            weakSelf.carDirectorTF.text=@"双向";
//        }
//    };
    [_DescriptionTV setTextFieldInputAccessoryView:_DescriptionTV frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    // Do any additional setup after loading the view from its nib.
}

- (BOOL) isNumber:(NSString *)text;
{
    NSString *regex =@"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if (![pred evaluateWithObject:text]) {
        NSLog(@"不是");
        return YES;
    }
    NSLog(@"是");
    return NO;
}

-(void)resultMessage:(NSString *)result
{
    _resultAlert=[[UIAlertView alloc] initWithTitle:@"提示" message:result delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [_resultAlert show];
}

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([_DescriptionTV.text isEqualToString:@"请输入事件描述："]) {
        _DescriptionTV.text=@"";
        _DescriptionTV.textColor=[UIColor blackColor];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0) {
        NSLog(@"取消");
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.text.length<1) {
        textView.text = @"请输入事件描述：";
        //textView.alpha=0.7;
        textView.textColor=[UIColor grayColor];
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden=NO;
}

-(void)AddchooseCityDirectorBtn
{
    UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [btn setBackgroundImage:[UIImage imageNamed:@"xiala"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(popCityList:) forControlEvents:UIControlEventTouchUpInside];
    
    self.carDirectorTF.rightView=btn;
    self.carDirectorTF.rightViewMode=UITextFieldViewModeAlways;
}

-(void)popCityList:(UIButton *)btn
{
    
    _citypop.popoverPresentationController.sourceView=btn;
    _citypop.popoverPresentationController.delegate=self;
    _citypop.popoverPresentationController.sourceRect=CGRectMake(-70, 0, 100, 210);
    _citypop.popoverPresentationController.permittedArrowDirections=NO;
    [self presentViewController:_citypop animated:YES completion:nil];
}

-(void)request
{
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getCurrentEventModel=[[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL=GetEventDataURL;
    getCurrentEventModel.DataValue = [self dataValueJson];
    getCurrentEventModel.UpdatedTime=@"2012-01-12 12:00:00";
    getCurrentEventModel.SystemCode=@"GuangleHighway";
    getCurrentEventModel.MethodName=@"ReportOtherEventBaseDetailInfo";
    
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        
        NSLog(@"%@",dataValueModel);
        self.code=[requestOutginseng.Code integerValue];
        if (self.code==001) {
            [SVProgressHUD showSuccessWithStatus:@"上报成功"];
           // [self resultMessage:@"上传成功"];
        }
    };
    if (!_loadImage) {
        [requestHelper RequestGinsengModel:getCurrentEventModel andPushController:self];
    }
    else
    {
        [self requestTestUpdateImage:getCurrentEventModel Image:_loadImage];
    }
    
}

-(void)requestTestUpdateImage:(RequestGinsengModel *)RequestGinseng Image:(UIImage *)LoadImage
{
    [SVProgressHUD showWithStatus:@"正在上传图片,请稍后......"];
    
    UIImage *image = LoadImage;
    
    NSDictionary *dic=[[NSDictionary alloc] init];
    
    dic=@{@"methodName":RequestGinseng.MethodName,@"updatedtime":RequestGinseng.UpdatedTime,@"systemcode":DefaultSystemCode,@"DataValue":RequestGinseng.DataValue};
    
    [BCNetAPIClient  uploadImage:GetEventDataURL andParameters:dic andImage:image progress:^(NSProgress *progress) {
        
    }success:^(id responseObject)
     {
         [SVProgressHUD showSuccessWithStatus:@"上报成功"];
         [self.navigationController popViewControllerAnimated:YES];
     }
                         failure:^(NSError *failure) {
                             [SVProgressHUD showSuccessWithStatus:@"上报失败"];
                             NSLog(@"%@",failure);
                             return ;
                             
                         }];
}

- (IBAction)MapPoint:(UIButton *)sender {
    
    [self.navigationController pushViewController:_map animated:YES];
    
}

-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}

-(NSString *)dataValueJson
{

    if (!_info.Latitude&&!_info.Longitude) {
        NSArray *arr=[[TableOperation shareInstance]  getePirNoTableOfRow:[@"K" stringByAppendingString:self.BeginPirTF.text]];
        for (PileInfo *pir in arr) {
            NSLog(@"%f,%f",pir.Latitude,pir.Longitude);
            _info.Latitude=pir.Latitude;
            _info.Longitude=pir.Longitude;
        }
    }
    
    //info.PileDistance=@"100";
    _info.IncidentDetail=self.DescriptionTV.text;
    _info.BeginPile=self.BeginPirTF.text;

    
    NSLog(@"%@.%@",_info.Latitude,_info.Longitude);

    if([self.carDirectorTF.text isEqualToString:@"广州方向"])
    {
        _info.RoadDerection=@"1";
    }
    if([self.carDirectorTF.text isEqualToString:@"湖南方向"])
    {
        _info.RoadDerection=@"2";
    }
    if([self.carDirectorTF.text isEqualToString:@"双向"])
    {
        _info.RoadDerection=@"3";
    }
    _info.IncidentSource=@"1";
    
    NSMutableDictionary *dic=_info.mj_keyValues;
    NSString *str=[dic mj_JSONString];
    
    ParModel *model=[[ParModel alloc] init];
    model.key=@"EventBaseInfo";
    model.value=str;
    
    NSMutableDictionary *jsonDic=model.mj_keyValues;
    NSString *json=[jsonDic mj_JSONString];
    
    NSString *strl=@"[";
    NSString *temp=[strl stringByAppendingString:json];
    NSString *str1r=@"]";
    NSString *JsonString=[temp stringByAppendingString:str1r];
    
    return JsonString;
    
}
- (void)report
{
    if (stringIsEmpty(_BeginPirTF.text)) {
        [_PromptUtil alert:@"开始桩号不能为空"];
        return;
    }
    if (stringIsEmpty(_DistanceTF.text)) {
        [_PromptUtil alert:@"桩距离不能为空"];
        return;
    }
    if (stringIsEmpty(_carDirectorTF.text)) {
        [_PromptUtil alert:@"行车方向不能为空"];
        return;
    }
    if (stringIsEmpty(_DescriptionTV.text)) {
        [_PromptUtil alert:@"事件描述不能为空"];
        return;
    }
    if ([_DescriptionTV.text isEqualToString:@"请输入事件描述："])
     {
         [_PromptUtil alert:@"请输入事件描述"];
     }
    if ([self isNumber:_BeginPirTF.text]) {
        [_PromptUtil alert:@"请输入整形数字开始桩号"];
        return;
    }
    if ([self isNumber:_DistanceTF.text]) {
        [_PromptUtil alert:@"请输入整形数字开始桩距离"];
        return;
    }
    
    [self request];
}


- (IBAction)chooseImage:(UIButton *)sender {
    
    
    if (_imageScrollview) {
        for (UIView *subView in _imageScrollview.subviews) {
            [subView removeFromSuperview];
        }
    }
    
    SGImagePickerController *picker = [[SGImagePickerController alloc] initWithRootViewController:self];
    
    //返回选择的缩略图
    [picker setDidFinishSelectThumbnails:^(NSArray *thumbnails) {
        _imageArray=thumbnails;
        for (int i=0;i<_imageArray.count;i++) {
            _img=_imageArray[i];
            //_loadImage=thumbnails[i];
            
            _iv=[[UIImageView alloc] initWithFrame:CGRectMake(2+(125+2)*i, 0, 125, 125)];
            _iv.image=_img;
            [_imageScrollview addSubview:_iv];
        }
        _imageScrollview.contentSize=CGSizeMake(thumbnails.count*125, 125);
        NSLog(@"缩略图%@",thumbnails);
        
    }];
    
    //返回选中的原图
    [picker setDidFinishSelectImages:^(NSArray *images) {
        for (int i=0;i<images.count;i++) {
            _loadImage=images[i];
        }
    }];
    [self presentViewController:picker animated:YES completion:nil];
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
